// 加载http模块
let http = require('http')
let Cheerio = require('cheerio')
let fs = require('fs')
let path = require('path')
//定义网络爬取的地址
let url = 'http://www.87g.com/pg/67193.html'
http.get(url, (res) => {
  let html = ''
  //获取页面数据
  res.on('data', (data) => {
    html += data;
  })
  console.log(html);
  res.on('end', () => {
    //过滤页面信息
    //TODO: 获取枪支的截图
    var listData = getMyowenPage(html)
    //TODO:打印信息
    prinfInfo(listData);
  })
}).on('error', () => {
  console.log('获取数据出错')
})

function getMyowenPage(html) {
  if (html) {
    var $ = Cheerio.load(html, {
      ignoreWhitespace: true
    })
    var imglist = $('.cont')
    //轮播图数据
    var slideListData = []
    //轮播图信息列表遍历
    $('.cont h4').each(function (index, items) {
      if (index < 8) {
        slideListData.push({
          name: $(this).text().trim(),
          list: []
        })
      }
    })
    $('.cont table tbody').each(function (index, items) {
      if (index >= 8) {
        return;
      }
      console.log(this == $('.cont table tbody')[0]);
      var tr = $(items).find('tr:not(:nth-child(1))')
      tr.map(function (items) {
        dt1 = $(this).find('img').attr('src')
        dt2 = $(this).find('td:nth-child(2)').text().trim()
        dt3 = $(this).find('td:nth-child(3)').text().trim()
        dt4 = $(this).find('td:nth-child(4)').text().trim()
        slideListData.map((items, i, obj) => {
          if (i < 8 && i == index) {
            items.list.push({
              'img': dt1,
              'name': dt2,
              'attack': dt3,
              'intro': dt4
            })
          }
        })
      })
    })
  }
  return slideListData
}

function prinfInfo(param) {
  param.map((items) => {
    for (let i of items.list) {
      // console.log(i.img, i.name, i.attack, i.intro);
    }
  })
  fs.writeFile('chiji.json', JSON.stringify(param), function () {

  })
  fs.readFile('chiji.json', 'utf-8', function (err, data) {
    if (err) {
      throw err;
    }
    // console.log(data);
  })
}